package service

import (
	"context"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"github.com/toolkits/pkg/logger"
	"io"
	"os"
)

func GetImagesList(dockerCli *client.Client) (images []types.ImageSummary, err error) {
	ctx := context.Background()
	images, err = dockerCli.ImageList(ctx, types.ImageListOptions{All: true})
	if err != nil {
		logger.Error(err)
		return images, err
	}
	return images, nil
}

func GetImage(cli *client.Client, imageID string) (imageInfo types.ImageInspect, err error) {
	ctx := context.Background()
	imageInfo, _, err = cli.ImageInspectWithRaw(ctx, imageID)
	if err != nil {
		return imageInfo, err
	}
	return imageInfo, nil
}

func PullImages(cli *client.Client, imageList []string) (pullImageListResponse PullImageListResponse, err error) {

	for _, imageName := range imageList {
		err = PullImage(cli, imageName)
		if err != nil {
			pullImageListResponse.ErrImageList = append(pullImageListResponse.ErrImageList, imageName)
		} else {
			pullImageListResponse.SuccessImageList = append(pullImageListResponse.SuccessImageList, imageName)
		}
	}
	return pullImageListResponse, nil
}

// PullImage
// 拉取指定镜像
func PullImage(cli *client.Client, imageName string) error {
	ctx := context.Background()

	reader, err := cli.ImagePull(ctx, imageName, types.ImagePullOptions{})
	if err != nil {
		logger.Error(err)
		return err
	}
	_, err = io.Copy(os.Stdout, reader)
	if err != nil {
		logger.Error(err)
		return err
	}
	return nil
}

func DeleteImage(cli *client.Client, imageId string) (imageDeleteResponseItems []types.ImageDeleteResponseItem, err error) {
	ctx := context.Background()
	imageDeleteResponseItems, err = cli.ImageRemove(ctx, imageId, types.ImageRemoveOptions{Force: true})
	if err != nil {
		fmt.Println(err)
		return imageDeleteResponseItems, err
	}
	return imageDeleteResponseItems, nil
}

func AddNewTag(cli *client.Client, sourceImageName string, newImageName string) error {
	ctx := context.Background()
	err := cli.ImageTag(ctx, sourceImageName, newImageName)
	if err != nil {
		return err
	}
	return nil
}
